//index.js
//获取应用实例
var App = getApp()
var Api = require("../../common/api/api.js")

var imgArr = []; //这个数组用来临时存储图片数据
Page({
  data: {
    userInfo: {},
    addressData: null,
    userStatus: {},
    addRessName: false,
    content: '',
    title: '',
    imgStr: null,
    httpImg: [],
    latitude: '',
    chooseImageUrl: [], //绑定到页面的数据
    imgCount: 0, //图片的张数
    imgLenght: 0,
    chooseImagehid: false,
    uploadimgindex: 0,//当前上传第几张
    uploadimgnameArr: [], //上传图片文件名称


    chooseVideohid: false,
    videoCover: '',
    videoUrl: '',

    //添加标签显示或隐藏
    addTag: false,
    tag: "添加标签",
    tagEdit: "",


    //----------------
    statusBarHeight: 50,
    showInput: false, //控制输入栏
    id:0, //圈子主键ID

    type: 0, //tab类型 1：阅读；2：商品；3：直播；
  },
  onLoad: function (e) {
    this.setData({
      id: e.id,
      type: e.type,
    });

    console.log(imgArr);
    imgArr = [];
  },

  /**
   * 这里触发图片上传的方法
   */
  formSubmit: function (e) {
    var that = this


    //评价的内容
    var content = e.detail.value.content;
    if (content == '') {
      App.showError("你填写你的需求");
      return;
    }

    var addTag = that.data.addTag;
    var tag = that.data.tag;

    console.log(" - - addTag - - ",addTag);
    console.log(" - - tag - - ", addTag);


    if (addTag && (tag == "添加标签" || tag == "")){
      App.showError("请添加标签");
      return;
    }


    var pics = that.data.chooseImageUrl;

    // that.data.uploadimgnameArr = {};
    wx.showLoading({
      title: '提交中...',
    })
    setTimeout(function () {
      wx.hideLoading()
    }, 2000)


    wx.uploadFile({
      url: Api.host + "/api/fileUpload/upload",
      filePath: pics[that.data.uploadimgindex],
      name: 'file',
      formData: {},
      method: 'POST',
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        var obj = JSON.parse(res.data);
        console.log("上传后的数据：",obj);
        if (obj.code == 0) {
          that.data.uploadimgnameArr.push(obj.data);
          console.log("上传后的数据：", that.data.uploadimgnameArr)
        } else {
          console.log(obj)
        }
      },
      fail: (res) => {
        console.log(res)
      },
      complete: () => {

        var uploadTempindex = that.data.uploadimgindex + 1;
        that.setData({
          uploadimgindex: uploadTempindex
        })
        if (that.data.uploadimgindex >= pics.length) {
          console.log('上传完成')
          that.data.uploadimgindex = 0;

          console.log("所有图片上传完成后地址：", that.data.uploadimgnameArr)

          //请求参数封装
          var data = {
            content: content,
            id: that.data.id,    //空间ID
            imgNames: that.data.uploadimgnameArr,
            openid: wx.getStorageSync("openid"),
            synDemandHall: addTag, //是否同步到需求大厅；true：同步， ,
            tag: tag,  // 标签值；synDemandHall 为true时，传入标签值,
            type: that.data.type, 
          }
          var params = JSON.stringify(data)
          Api.publishTopic(params).then(function (result) {
            if (result.data.code == 0){
              // 跳转到指定页面
              wx.redirectTo({
                url: '../sharespace/sharespace?id='+that.data.id,
              })
            }else{
              wx.hideLoading();
            }
          }).catch(function (error) {
            console.log(error)
          })
        } else {
          that.formSubmit(e);
        }
      }
    })

  },

  // 清除
  formReset: function () {
    console.log('form发生了reset事件')
  },
  // 输入内容
  listenercontent: function (e) {
    var tempc = e.detail.value;

    if (tempc.length > 10) {
      tempc = tempc.substring(0, 9)
    }
    console.log(tempc)
    that.setData({
      content: tempc
    })
  },

  // 选择地理位置
  bindAddress: function () {
    var that = this

    // 取消选择地理位置后获取当前人经纬度调用后台接口接收当前地理位置
    wx.chooseLocation({
      success: function (lb) {
        //console.log(lb)
        that.data.addressData = lb
        that.setData({
          addRessName: lb.name
        })
        //console.debug(that.data.addressData)  
      },
      cancel: function (lb) // 取消选择
      {
        //that.data.addressData = that.data.userStatus
      },
      fail: function (lb) {
        console.log(lb)
      }
    })
  },

  /**
   * 图片上传
   */
  chooseImage: function (e) {
    var that = this

    //wx.chooseImage 不多介绍看文档
    wx.chooseImage({
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],//压缩图
      count: 6 - that.data.imgCount,
      success: function (res) {

        var tempFilePaths = res.tempFilePaths;
        var len = that.data.imgCount + tempFilePaths.length
        //len 是此时已有的张数和本次上传的张数的和，也就是本次操作完成页面应该有的张数，因为用户可能会多次选择图片，所以每一次的都要记录下来。

        for (var i = 0; i < tempFilePaths.length; i++) {
          //将api 返回的图片数组push进一开始的imgArr，一定要循环一个个添加，因为用户上传多张图直接push就会多个路径在imgArr的同一个元素里。报错
          imgArr.push(tempFilePaths[i]);
        }
        var addImagehid = false
        if (len >= 6) {
          addImagehid = true
        }
        //将此时的图片长度和存放路径的数组加到要渲染的数据中
        that.setData({
          imgCount: len,
          chooseImageUrl: imgArr,
          chooseImagehid: addImagehid
        })

      }
    })
  },

  /**
   * 视频上传
   */
  chooseVideo: function (e) {
    var _this = this

    //wx.chooseVideo 不多介绍看文档
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {

        // _this.setData({
        //   videoCover:res.thumbTempFilePath,
        //   video:res.tempFilePath,
        // });
        _this.uploder(res.tempFilePath);
      }
    })
  },


  uploder: function (video) {
    let _this = this;

    /**
     * 视频上传
     */
    wx.uploadFile({
      url: App.data.topicUrl + "/store/api/uploadFile",
      filePath: video,
      name: 'file',
      formData: {},
      method: 'POST',
      header: { "Content-Type": "multipart/form-data" },
      success: function (res) {
        var obj = JSON.parse(res.data);
        if (obj.code == 0) {
          console.log("上传后的数据：", obj.data)
          _this.setData({
            videoCover: obj.data.videoCover,
            videoUrl: obj.data.videoUrl,
          });
        } else {
          console.log(obj)
        }
      },
      fail: (res) => {
        console.log(res)
      },
      complete: () => { }
    })
  },

  previewImage: function (e) // 显示图片大图
  {
    var current = e.target.dataset.index
    console.log(current)
    console.log(imgArr[current])
    if (current != undefined) {
      wx.previewImage({
        current: imgArr[current],
        urls: imgArr
      })
    }

  },
  bindLoding: function () { // LOADING加载
    wx.showToast({
      title: '图片上传中',
      icon: 'loading'
    })
  },
  //点关闭按键
  deleteImg: function (e) {
    var mylen = this.data.chooseImageUrl.length; //当前渲染的数组长度

    var myindex = e.currentTarget.dataset.index; //当前点击的是第几张图片 data-index
    imgArr.splice(myindex, 1) //将这张图充存放图片的数组中删除

    this.setData({
      imgCount: mylen - 1, //长度减一
      chooseImageUrl: imgArr //将删除图片后的数组赋给要渲染的数组
    })
  },


  //同步到需求大厅
  aync:function(){
    var flag = this.data.addTag;
    if (flag){
      this.setData({
        addTag: false,
      });
    }else{
      this.setData({
        addTag: true,
      });
    }
  },


  //点击出现输入框
  showInput: function () {
    this.setData({
      showInput: true
    })
  },
  //隐藏输入框
  onHideInput: function () {
    this.setData({
      showInput: false
    })
  },

  inputeidt: function (e) {
    this.setData({
      tagEdit: e.detail.value,
    });
  },


//添加标签
  sendTextMsg:function(){
    if(this.data.tagEdit!=''){
      this.setData({
        tag: this.data.tagEdit,
      });
    }
  },
  send: function () {
    if (this.data.tagEdit != '') {
      this.setData({
        tag: this.data.tagEdit,
      });
    }
  },


})